import { AxiosResponse, InternalAxiosRequestConfig } from './types'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { objToFormData } from '@/utils'
import { isEmpty } from 'lodash-es'

// 默认请求拦截器
const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (
    config.method === 'post' &&
    config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
  ) {
    config.data = qs.stringify(config.data)
  } else if (
    TRANSFORM_REQUEST_DATA &&
    config.method === 'post' &&
    config.headers['Content-Type'] === 'multipart/form-data' &&
    !(config.data instanceof FormData)
  ) {
    config.data = objToFormData(config.data)
  }
  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  return config
}

// 默认响应拦截器
const defaultResponseInterceptors = (response: AxiosResponse) => {
  // console.log('defaultResponseInterceptors执行了', response)

  // 处理文件流响应
  if (response?.config?.responseType === 'blob') {

    if (response.status === 200) {
      return response
    }else if(response.status === 400){
      ElMessage.error( "导出失败")
    }

    // return response
  }else if (response?.config?.responseType === 'arraybuffer') {
    return response
  }

  const { status } = response
  // console.log('defaultResponseInterceptors', status, response.data)

  const { rspcod, rows, map, obj, msg, records, code, data } = response.data
  // console.log('response.data', response.data, code)

  // 首先处理HTTP错误状态码 (非2xx)
  if (status < 200 || status >= 300) {
    return handleErrorResponse(response)
  }

  // 新接口返回格式处理 (code字段)
  if (code === 200) {
    // console.log(9999, {
    //   data: data?.rows || data,
    //   total: data?.total || 0
    // })
    return {
      data: data?.rows || data,
      total: data?.total || 0,
      code: code || 200,
    }
  }

  if (code == 299) {
    return {
      data: data,
      code: code || 299,
    }
  }

  // 旧接口返回格式处理 (rspcod字段)
  if (code == SUCCESS_CODE) {
    if (rows) {
      return {
        data: rows,
        total: records,
        obj
      }
    }
    if (!isEmpty(map)) {
      return map
    }
    if (!isEmpty(obj)) {
      return obj
    }
    return {}
  }

  // 业务错误状态码处理
  return handleBusinessError(response, rspcod, msg)
}

// 统一处理HTTP错误
const handleErrorResponse = (response: AxiosResponse) => {
  const { status, data } = response
  console.log('handleErrorResponse', status, data)

  const { rspcod, msg } = data || {}
  // console.log(data,88888888);


  switch (status) {
    case 401:
      // 这里直接处理401，不再返回Promise.reject，避免被外层拦截器捕获
      if (rspcod === '102') {
        return handleTokenRefresh(response.config)
      } else {
        triggerLogout("登录已过期，请重新登录")
      }
      break
    case 403:
      ElMessage.error(msg || "无权访问该资源")
      break
    case 500:
      ElMessage.error(msg || "服务器内部错误")
      break
    default:
      ElMessage.error(msg || `请求失败(${status})`)
  }

  // 返回一个rejected promise，但不会被外层拦截器再次处理
  return Promise.reject({
    response,
    message: msg || `请求失败(${status})`,
    handled: true // 标记已处理，避免重复处理
  })
}

// 统一处理业务错误
const handleBusinessError = (response: AxiosResponse, rspcod?: string, msg?: string) => {


  switch (rspcod) {
    case '201':
      ElMessage.error(msg || "操作失败")
      break
    case '102':
      triggerLogout("登录超时，请重新登录")
      break
    case '103':
      triggerLogout("账号已在其他设备上登录")
      break
    default:
      ElMessage.error(msg || "系统出错")
  }

  return Promise.reject(response)
}

// 刷新 Token 处理
const handleTokenRefresh = async (config: any) => {
  try {
    const userStore = useUserStoreWithOut()
    // const newToken = await userStore.refreshToken()
    // config.headers.Authorization = `Bearer ${newToken}`
    // return axiosInstance(config)
  } catch (error) {
    triggerLogout("Token刷新失败，请重新登录")
    return Promise.reject(error)
  }
}

// 触发登出统一方法
const triggerLogout = (message: string, delay = 1000) => {
  ElMessage.error(message)
  setTimeout(() => {
    const userStore = useUserStoreWithOut()
    userStore.logout()
  }, delay)
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
